package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.vo.AuthRequest;
import cn.edu.tju.elm.vo.AdminAuthRequest;
import cn.edu.tju.elm.vo.UserWithAuthoritiesRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.tju.elm.service.UserService;
import cn.edu.tju.core.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @PostMapping
    public HttpResult create(@RequestBody User user) {
        if (user.getPassword() != null && user.getPassword().length() > 0) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        boolean saved = userService.save(user);
        return saved ? HttpResult.ok(user) : HttpResult.fail("create failed");
    }

    @PutMapping("/{id}")
    public HttpResult update(@PathVariable Integer id, @RequestBody User user) {
        user.setId(id);
        if (user.getPassword() != null && user.getPassword().length() > 0) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        boolean updated = userService.updateById(user);
        return updated ? HttpResult.ok(user) : HttpResult.fail("update failed");
    }

    @DeleteMapping("/{id}")
    public HttpResult delete(@PathVariable Integer id) {
        boolean removed = userService.removeById(id);
        return removed ? HttpResult.ok(true) : HttpResult.fail("delete failed");
    }

    @GetMapping("/{id}")
    public HttpResult get(@PathVariable Integer id) {
        User user = userService.getById(id);
        return user != null ? HttpResult.ok(user) : HttpResult.fail("not found");
    }

    @GetMapping("/list")
    public HttpResult list(@RequestParam(required = false) String username,
                       @RequestParam(required = false) String account,
                       @RequestParam(required = false) Integer role,
                       @RequestParam(defaultValue = "1") long page,
                       @RequestParam(defaultValue = "10") long size) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (username != null && username.trim().length() > 0) {
            qw.like("username", username.trim());
        }
        if (account != null && account.trim().length() > 0) {
            qw.eq("account", account.trim());
        }
        if (role != null) {
            qw.eq("role", role);
        }
        Page<User> p = userService.page(new Page<>(page, size), qw);
        return HttpResult.ok(p);
    }

    @PostMapping("/register")
    public HttpResult register(@RequestBody User user) {
        if (user == null || user.getPhone() == null || user.getPassword() == null) {
            return HttpResult.fail("手机号或密码不能为空");
        }
        User exists = userService.getOne(new QueryWrapper<User>().eq("phone", user.getPhone()));
        if (exists != null) {
            return HttpResult.fail("手机号已经被注册");
        }
        // 设置默认值
        if (user.getRole() == null) {
            user.setRole(0); // 默认用户身份
        }
        if (user.getGender() == null) {
            user.setGender(0); // 默认未知性别
        }
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        boolean saved = userService.save(user);
        return saved ? HttpResult.ok(user) : HttpResult.fail("注册失败");
    }

    @PostMapping("/login")
    public HttpResult login(@RequestBody AuthRequest req) {
        if (req == null || req.getPhone() == null || req.getPassword() == null) {
            return HttpResult.fail("手机号或密码不能为空");
        }
        User user = userService.getOne(new QueryWrapper<User>().eq("phone", req.getPhone()));
        if (user == null) {
            return HttpResult.fail("用户不存在");
        }
        boolean match = passwordEncoder.matches(req.getPassword(), user.getPassword());
        if (!match) {
            return HttpResult.fail("密码错误");
        }
        user.setPassword(null);
        return HttpResult.ok(user);
    }

    @PostMapping("/createWithAuthorities")
    public HttpResult createUserWithAuthorities(@RequestBody UserWithAuthoritiesRequest request) {
        if (request == null) {
            return HttpResult.fail("请求参数不能为空");
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(request.getUsername());
        user.setFirstName(request.getFirstName());
        user.setLastName(request.getLastName());
        user.setAuthorities(request.getAuthorities());
        
        // 这里可以添加保存用户和权限的逻辑
        // 目前只是返回创建的用户对象作为示例
        return HttpResult.ok(user);
    }

}


